import { Card, Button, Table, Popconfirm, message, Modal, Form, Input, Upload } from "antd";
import { PlusOutlined, WalletFilled, DeleteFilled, LoadingOutlined } from "@ant-design/icons"
import { useEffect, useState } from "react";
import type { UploadChangeParam } from 'antd/es/upload';
import type { UploadFile, UploadProps, RcFile } from 'antd/es/upload/interface';


//类型
import type {
    trademarkRecordsItemType
} from "@/api/product/model/trademarkType"
//api
import {
    requestTrademarkList,
    requestDeleteTrademark,
    requestEditTrademark,
    requestAddTrademark
} from "@/api/product/trademark"
import { setTextRange } from "typescript";


//组件
export default function Trademark() {
    //获取环境变量
    const prefix = process.env.REACT_APP_APP
    //获取表单实例
    const [form] = Form.useForm()

    //表格数据
    const [tableData, setTableData] = useState<trademarkRecordsItemType[]>([])
    const [page, setPage] = useState<number>(1)
    const [limit, setLimit] = useState<number>(3)
    const [total, setTotal] = useState<number>(0)
    const [isrepect, setIsrepect] = useState(false)

    //对话框
    const [isShowModal, setIsShowModal] = useState<boolean>(false)
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const [tmName, setTmName] = useState<string>("")
    const [trademarkId, setTrademarkId] = useState<number>(0)


    //初始化和页码数据改变发送请求
    useEffect(() => {
        getTrademarkList()
    }, [page, limit, isrepect])

    //1.请求分页列表的回调
    const getTrademarkList = async () => {
        //请求分页数据
        const result = await requestTrademarkList(page, limit)
        //保存总页树
        setTotal(result.total)
        //保存数据
        setTableData(result.records)
    }

    //2.删除
    const deleteTrademark = (id: number) => {
        //真正的事件回调
        return async () => {
            //删除请求
            await requestDeleteTrademark(id)
                .then(() => {
                    message.success("删除成功!")
                    //重新请求分页列表
                    setIsrepect(!isrepect)
                })
                .catch(() => message.error("删除失败!"))
        }
    }

    //4.添加
    const addTrademark = () => {
        //删除id
        setTrademarkId(0)
        //清空表单信息(和校验信息)
        form.resetFields()
        //清空图片
        setImageUrl('')
        //展示对话框
        setIsShowModal(true)
    }
    //5.修改
    const editTrademark = (data: trademarkRecordsItemType) => {
        return async () => {
            //先清空表单(清空校验信息)
            form.resetFields()
            //保存id
            setTrademarkId(data.id)
            //保存品牌名
            setTmName(data.tmName)
            //保存图片
            setImageUrl(data.logoUrl)
            //回填表单数据
            form.setFieldsValue({ 'tmName': data.tmName })

            //展示对话框
            setIsShowModal(true)
        }
    }

    //6.保存
    const saveHandel = () => {
        //先校验表单校验
        form.validateFields()
            .then(async () => {
                //校验图片
                if (!imageUrl) {
                    message.error("请上传图片"!)
                    return
                }

                //都校验成功开始发送请求
                if (trademarkId) {
                    //修改请求
                    await requestEditTrademark(trademarkId, (imageUrl as string), tmName)
                        .then(() => {
                            message.success("修改成功!")
                            //关闭对话框
                            setIsShowModal(false)
                            //重新渲染
                            setIsrepect(!isrepect)
                        })
                        .catch((e) => message.error(e))
                    return
                }
                //新增请求
                await requestAddTrademark((imageUrl as string), tmName)
                    .then(() => {
                        message.success("新增成功!")
                        //关闭对话框
                        setIsShowModal(false)
                        //重新渲染
                        setIsrepect(!isrepect)
                    })
                    .catch((e) => message.error(e))

            })
            .catch(() => { })
    }


    //7.上传图片
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false);
            //保存图片
            setImageUrl(info.file.response.data)
        }
    };

    //上传按钮
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    // 设置如何将 event 的值转换成字段值
    const normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e
        }
        return e && e.fileList;
    };

    //表格中列数据的配置
    const columns = [
        {
            title: '序号',
            width: 120,
            align: "center" as "center",
            render(_: any, __: any, index: number) {
                return index + 1
            }
        },
        {
            title: '品牌名称',
            dataIndex: 'tmName',
        },
        {
            title: '品牌LOGO',
            render(_: any, data: trademarkRecordsItemType) {
                return <img width={120} src={data.logoUrl} alt="" />
            }
        },
        {
            title: '操作',
            render(_: any, data: trademarkRecordsItemType) {
                return (
                    <div>
                        <Button onClick={editTrademark(data)} type="primary" style={{ marginRight: '10px' }} icon={<WalletFilled />}>修改</Button>

                        <Popconfirm
                            title="是否要删除?"
                            onConfirm={deleteTrademark(data.id)}
                            onCancel={() => message.warning("已取消删除")}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="primary" danger={true} style={{ marginRight: '10px' }} icon={<DeleteFilled />}>删除</Button>
                        </Popconfirm>

                    </div>
                )
            }
        },
    ];

    return (
        <Card style={{ margin: "10px 20px" }} title={<Button onClick={addTrademark} type="primary" icon={<PlusOutlined />}>添加</Button>}>
            <Table
                dataSource={tableData}
                columns={columns}
                bordered={true}
                rowKey="id"
                pagination={{
                    current: page,
                    pageSize: limit,
                    total: total,
                    pageSizeOptions: [5, 10, 15, 20, 100],
                    showSizeChanger: true,

                    onChange(page: number, limit: number) {
                        setPage(page)
                        setLimit(limit)
                    },

                    showTotal(total) {
                        return `总共有${total}条数据`
                    },

                }}
            />

            {/* 对话框 */}
            <Modal title={trademarkId ? '修改品牌' : '新增品牌'} visible={isShowModal} onOk={saveHandel} onCancel={() => setIsShowModal(false)}>
                <Form
                    form={form} //获取表单实例
                    validateTrigger="onBlur"
                >
                    <Form.Item
                        label="品牌名称"
                        name="tmName"
                        rules={[{ required: true, message: '品牌名称不能为空!' }]}
                    >
                        <Input onChange={e => setTmName(e.target.value)
                        } />
                    </Form.Item>
                    <Form.Item
                        label="品牌LOGO"
                        // name="logURL"
                        // rules={[{ required: true, message: '请上传图片!' }]}
                        valuePropName="fileList"
                        getValueFromEvent={normFile}
                    >
                        {<Upload
                            listType="picture-card"
                            showUploadList={false}
                            action={`${prefix}/admin/product/fileUpload`}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
                        </Upload>}
                    </Form.Item>
                </Form>
            </Modal>

        </Card>
    )
}
